package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.demo.PayResult;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.AESUtil;
import com.sxm.yiwei.utils.BottomDialogOnclickListener;
import com.sxm.yiwei.utils.BottomDialogView;
import com.sxm.yiwei.utils.DialogUtil;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.Map;

public class YiweiPayActivity extends BaseActivity implements View.OnClickListener{

    private static final int SDK_PAY_FLAG = 1;
    private ImageView yiback;
    private TextView paytype;
    private TextView paymoney;
    private TextView payno;
    private Button paybt;
    private EditText inpayword;
    private int num;
    private Double dmoney;
    private String type;
    private String format;
    private String bonusId;
    private String word;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;

    private String inword1;
    private CheckBox yiweipay;
    private CheckBox zhifubaopay;
    private RelativeLayout layyiweipay;
    private RelativeLayout layzhifupay;
    private TextView wText;
    private TextView zText;
    private int t;
    private String data;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult payresult = new PayResult((Map<String, String>)msg.obj);
            String resultStatus = payresult.getResultStatus();
            if (resultStatus.equals("9000")){
                Toast.makeText(YiweiPayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
            }else if (resultStatus.equals("8000")){
                Toast.makeText(YiweiPayActivity.this, "支付处理中", Toast.LENGTH_SHORT).show();

            }else if (resultStatus.equals("4000")){
                Toast.makeText(YiweiPayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

            }else if (resultStatus.equals("5000")){
                Toast.makeText(YiweiPayActivity.this, "订单重复提交", Toast.LENGTH_SHORT).show();

            }else if (resultStatus.equals("6002")){
                Toast.makeText(YiweiPayActivity.this, "请检查你的网络是否启", Toast.LENGTH_SHORT).show();

            }else {
                Toast.makeText(YiweiPayActivity.this, "请稍等，支付结果获取中", Toast.LENGTH_SHORT).show();

            }
        }
    };
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yiwei_pay);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid","1");
        userId = sharedPreferences.getString("userId", "0");
        token = sharedPreferences.getString("token", "2");
        initYiweiView();
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        String number = intent.getStringExtra("number");
        num = Integer.parseInt(number);
        String money = intent.getStringExtra("money");
        dmoney = Double.valueOf(money);
        DecimalFormat df = new DecimalFormat(".##");
        format = df.format(dmoney);
        bonusId = intent.getStringExtra("bonusId");
        // 设置显示
        paytype.setText(type);
        paymoney.setText(money);
        payno.setText(number);

    }

    private void initYiweiView() {
        yiback = (ImageView) findViewById(R.id.yiwei_pay_back);
        paytype = (TextView) findViewById(R.id.yiwei_paytype);
        paymoney = (TextView) findViewById(R.id.yiwei_paymoney);
        payno = (TextView) findViewById(R.id.yiwei_payno);
        paybt = (Button) findViewById(R.id.yiwei_paybt);
        yiweipay = (CheckBox) findViewById(R.id.yiwei_pay_weixinbox);
        zhifubaopay = (CheckBox) findViewById(R.id.yiwei_pay_zhifubaobox);
        layyiweipay = (RelativeLayout) findViewById(R.id.yiwei_pay_vweixin);
        layzhifupay = (RelativeLayout) findViewById(R.id.yiwei_pay_vzhifu);
        wText = (TextView) findViewById(R.id.yiwei_pay_wqian);
        zText = (TextView) findViewById(R.id.yiwei_pay_zqian);
        backmain = (ImageView) findViewById(R.id.yipay_backmain);
        backmain.setOnClickListener(this);

        paybt.setOnClickListener(this);
        yiback.setOnClickListener(this);
        zhifubaopay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                layzhifupay.setVisibility(View.VISIBLE);
                layyiweipay.setVisibility(View.INVISIBLE);
                zText.setText(format);
                t = 1;// 支付宝支付
                if (zhifubaopay!=null){
                    yiweipay.setChecked(false);
                }
            }
        });

        yiweipay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                layzhifupay.setVisibility(View.INVISIBLE);
                layyiweipay.setVisibility(View.VISIBLE);
                wText.setText(format);
                t=2;// 钱包支付
                if (yiweipay!=null){
                    zhifubaopay.setChecked(false);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.yiwei_paybt:
                if (t==1){
                    sendBook(format);
                }else if (t==2){
                    showDialog();
                }


                break;
            case R.id.yiwei_pay_back:
                finish();
                break;
            case R.id.yipay_backmain:
                startActivity(new Intent(YiweiPayActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
        }
    }


        // 支付  输入支付密码
    private void showDialog() {
        DialogUtil.showBottomDialog(YiweiPayActivity.this, R.id.activity_show_bottom_dialog, new BottomDialogOnclickListener() {
            @Override
            public void onPositiveClick(String contentStr, BottomDialogView dialogView) {
                payMoney(contentStr);
                // 点击后消失
                dialogView.dismiss();
            }
        });
    }
        // 钱包支付方法
    private void payMoney(String s) {
        try {
            word = AESUtil.encryptAES(s);

        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.HOPE_SEND_YIWEIPAY);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);

        JSONObject j = new JSONObject();
        j.put("payType","04");
        j.put("payPassword",word);
        j.put("bonusId",bonusId);
        j.put("total_amount",format);
        params.setBodyContent(j.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                JSONObject object = JSON.parseObject(result);
                String status = object.getString("status");
                if (status.equals("1")){
                    Toast.makeText(YiweiPayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    finish();
                }else {
                    String failure = object.getString("failure");
                    if (failure.equals("1016")){
                        AlertDialog.Builder builder = new AlertDialog.Builder(YiweiPayActivity.this,R.style.NoBackGroundDialog);
                        View view = LayoutInflater.from(YiweiPayActivity.this).inflate(R.layout.cancel_servicedialog, null);
                        builder.setView(view);
                        Button cancelbt = (Button) view.findViewById(R.id.cancel_cancelbt);
                        Button surebt = (Button) view.findViewById(R.id.cancel_surebt);
                        TextView t2 = (TextView) view.findViewById(R.id.cancel_t2);
                        t2.setText("余额不足，请充值");
                        final AlertDialog dialog = builder.create();
                        cancelbt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        surebt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(YiweiPayActivity.this,MineAccountJoinMoney.class));
                                dialog.dismiss();
                            }
                        });
                        dialog.show();

                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(YiweiPayActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
        // 支付宝支付方法
        public void sendBook(String money) {
            RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.HOPE_SENG_ALIPAY);
            params.setHeader("Content-Type","application/json");
            params.setHeader("token", token);
            params.setHeader("appId", appId);
            params.setHeader("userId", userId);
            final JSONObject j = new JSONObject();
            j.put("payType","04");
            j.put("bonusId",bonusId);
            j.put("total_amount", money);
            params.setBodyContent(j.toJSONString());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(final String result) {
                    JSONObject obj = JSON.parseObject(result);
                    data = obj.getString("data");
                    final Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            PayTask payTask = new PayTask(YiweiPayActivity.this);
                            Map<String, String> map = payTask.payV2(data, true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = map;
                            mHandler.sendMessage(msg);


                        }
                    };
                    Thread payThread = new Thread(runnable);
                    payThread.start();
                    Toast.makeText(YiweiPayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();

                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Toast.makeText(YiweiPayActivity.this, "支付失败,请重新支付", Toast.LENGTH_SHORT).show();
                    ErrType.errType(YiweiPayActivity.this,ex);
                }
                @Override
                public void onCancelled(CancelledException cex) {
                }
                @Override
                public void onFinished() {

                }
            });




        }

}
